package com.generator;

import cn.hutool.db.Db;
import com.zaxxer.hikari.HikariDataSource;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 数据库工具类
 * </p>
 *
 * @package: com.generator.code.utils
 * @description: 数据库工具类
 * @author: yangkai.shen
 * @date: Created in 2019-03-22 10:26
 * @copyright: Copyright (c) 2019
 * @version: V1.0
 * @modified: yangkai.shen
 */
public class DbUtil {


    public static final ConcurrentHashMap<Integer,Db> dbs = new ConcurrentHashMap();

    public static Db getDb(String url, String user, String pwd){
        int key = user.concat(url).hashCode();
        if (!dbs.containsKey(key)){
            synchronized (dbs){
                if (!dbs.containsKey(key)){
                    HikariDataSource dataSource = DbUtil.buildFromTableRequest(url,user,pwd);
                    Db db = new Db(dataSource);
                    dbs.put(key,db);
                }
            }
        }
        return dbs.get(key);
    }




    public static HikariDataSource buildFromTableRequest(String url, String user, String pwd) {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(pwd);
        dataSource.setAutoCommit(true);
        dataSource.setMinimumIdle(1);
        dataSource.setIdleTimeout(60000);
        dataSource.setConnectionTestQuery("SELECT 1 FROM DUAL ");
        dataSource.setMaximumPoolSize(5);
        dataSource.setConnectionTimeout(30000);
        return dataSource;
    }

}
